using System;
using System.IO;
using System.Reflection;
using System.Threading;
using LoggingMagic.Tests.Consts;
using NUnit.Framework;
using TestAssemblyInterfaces;

namespace LoggingMagic.Tests.Integration.StaticMethodTests
{
    [SetUpFixture]
    internal class Initializer
    {
        private AppDomain _domain;

        private static Assembly _assembly;

        [SetUp]
        public void Setup()
        {
            _domain = AppDomain.CreateDomain("staticMethodTests2", null, new AppDomainSetup
            {
                ApplicationBase = Environment.CurrentDirectory,
                DisallowBindingRedirects = false,
                DisallowCodeDownload = true,
                PrivateBinPath = Environment.CurrentDirectory,
            });

            File.Copy(Const.MainDll, Const.TempDll, true);

            var task = new LoggingTask
            {
                Assembly = Const.TempDll,
                References = null,
                RunFromExe = true,
                Injector = "StaticMethodCall"
            };
            task.Execute();

            _assembly = _domain.Load("TestAssembly");
        }

        public static ITestClass GetTestAssemblyInstance()
        {
            Type type = _assembly.GetType("TestAssembly.TestClass");
            return (ITestClass)Activator.CreateInstance(type);
        }

        public static object GetClassWithCtorInstance()
        {
            Type type = _assembly.GetType("TestAssembly.ClassWithCtor");
            return Activator.CreateInstance(type);
        }

        public static void SetLogger(ILog logger)
        {
            var logClass = _assembly.GetType("TestAssembly.Logger");
            var loggerProperty = logClass.GetProperty("Log");
            loggerProperty.SetValue(null, logger, null);
        }

        [TearDown]
        public void TearDown()
        {
            AppDomain.Unload(_domain);
        }
    }
}